<template>
  <div class="index">
    <van-tabs v-model="activeIndex">
      <van-tab v-for="item in channels" :title="item.name" :key="item.id">
        <article-list :channel="item" @showMoreActive="hShowMoreActive"></article-list>
      </van-tab>
    </van-tabs>
    <div class="bar-btn" @click="showChannelEdit=true">
      <van-icon name="wap-nav"/>
    </div>
    <van-popup v-model="showMoreActive">
      <more-active ref="refMoreAction" @dislike="hDislike" @report="hReport"></more-active>
    </van-popup>
    <van-action-sheet v-model="showChannelEdit">
      <channel-edit
      @updateChannel="hUpdateChannel"
      @updateCurIndex="hUpdateCurIndex"
      :channels="channels"
      :activeIndex="activeIndex"
      ></channel-edit>
    </van-action-sheet>
  </div>
</template>

<script>
import { getChannels } from '@/api/channel'
import { dislikeArticle, reportArticle } from '@/api/article'
import ArticleList from './articleList.vue'
import MoreActive from './moreAction.vue'
import ChannelEdit from './channelEdit.vue'
export default {
  name: 'Home',
  data () {
    return {
      channels: [],
      articleId: null,
      activeIndex: 0,
      showChannelEdit: false,
      showMoreActive: false
    }
  },
  components: {
    ArticleList,
    MoreActive,
    ChannelEdit
  },
  created () {
    this.loadChannels()
  },
  methods: {
    hUpdateCurIndex (curIndex) {
      this.activeIndex = curIndex
    },
    hUpdateChannel (channel) {
      this.showChannelEdit = false
      const idx = this.channels.findIndex(item => item.id === channel.id)
      if (idx !== -1) {
        this.activeIndex = idx
      }
    },
    delArticle () {
      const eventObj = {
        articleId: this.articleId,
        channelId: this.channels[this.activeIndex].id
      }
      this.$eventBus.$emit('delArticle', eventObj)
    },
    async hReport (reportTypeId) {
      // 发请求
      await reportArticle(this.articleId, reportTypeId)
      // 关弹窗
      this.showMoreActive = false
      // 删文章
      this.delArticle()
    },
    async hDislike () {
      // 发请求
      await dislikeArticle(this.articleId)
      // 关弹窗
      this.showMoreActive = false
      // 删文章
      this.delArticle()
    },
    hShowMoreActive (id) {
      this.showMoreActive = true
      this.articleId = id
      // if (this.$refs.refMoreAction) {
      this.$refs.refMoreAction.isReport = false
      // }
    },
    async loadChannels () {
      try {
        const result = await getChannels()
        this.channels = result.data.data.channels
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
